package com.tanhua.admin.service;

import cn.hutool.crypto.digest.DigestUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bilibili.commons.Constants;
import com.bilibili.commons.utils.JwtUtils;
import com.bilibili.model.mongo.Admin;
import com.tanhua.admin.exception.BusinessException;
import com.tanhua.admin.mapper.AdminMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class AdminService extends ServiceImpl<AdminMapper, Admin> {

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 保存生成的验证码
     * @param uuid
     * @param code
     */
    public void saveCode(String uuid, String code) {
        String key = Constants.CAP_CODE + uuid;
        // 缓存验证码，10分钟后失效
        stringRedisTemplate.opsForValue().set(key,code, Duration.ofMinutes(10));
    }

    /**
     * 登录校验
     * @param paramMap
     * @Return: Map
     */
    public Map<String, String> login(Map<String, String> paramMap) {

        //参数校验 用户名和密码不能为空
        String username = paramMap.get("username");
        String password = paramMap.get("password");

        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)){

            throw new BusinessException("用户名或密码不能为空");
        }

        //校验验证码
        String verificationCode = paramMap.get("verificationCode");

        if (StringUtils.isEmpty(verificationCode)){

            throw new BusinessException("验证码不能为空");
        }

        //redis中的验证码
        String uuid = paramMap.get("uuid");

        String key = Constants.CAP_CODE + uuid;

        String codeInRedis = stringRedisTemplate.opsForValue().get(key);

        log.info("verificationCode:{},codeInRedis:{}", verificationCode, codeInRedis);

        //判断验证码是否存在 不存在验证码失效了 重新获取
        if (StringUtils.isEmpty(codeInRedis)) {

            throw new BusinessException("请重新获取验证码");
        }

        //两个验证码是否相同
        if (!verificationCode.equals(codeInRedis)){

            throw new BusinessException("验证码错误");
        }

        //相同删除redis中的验证码
        stringRedisTemplate.delete(key);

        //密码加密后  看在数据库中是否存在
        String md5Password = DigestUtil.md5Hex(password);

        Admin admin = query().eq("username", username).eq("password", md5Password).one();

        //不存在报错
        if (admin == null){

            throw new BusinessException("用户名或密码错误");
        }

        //存在 生成token 存入redis
        String token = JwtUtils.createToken(admin.getId(), username);

        //拼接token
        String tokenKey = "TOKEN_" + token;
        String jsonString = JSON.toJSONString(admin);

        stringRedisTemplate.opsForValue().set(tokenKey, jsonString, 30, TimeUnit.MINUTES);

        Map<String, String> resultMap = new HashMap<>();

        resultMap.put("token", token);

        return resultMap;
    }
}
